﻿namespace EasyGo.Controllers
{
    using System;
    using System.Threading;
    using System.Web.Mvc;
    using EasyGo.Common.Commands;
    using EasyGo.Common.Queries;
    using EasyGo.Logic;
    using EasyGo.Models;
    using EasyGo.Utils;

    public class CustomersController : EasyGoJsonController
    {
        private readonly ICustomerQueries customerQueries;

        private readonly ICustomersManager customerManager;

        public CustomersController(ICustomerQueries customerQueries, ICustomersManager customerManager)
        {
            this.customerQueries = customerQueries;
            this.customerManager = customerManager;
        }

        public virtual ActionResult GetAll()
        {
            var response = new JsonResponse(true, this.customerQueries.GetAllCustomers());
            return response.ToActionResult();
        }

        public virtual ActionResult Find(int id)
        {
            var response = new JsonResponse();
            var customer = this.customerQueries.FindCustomer(id);
            if (customer != null)
            {
                response.Response = customer;
            }
            else
            {
                response.Fail("Customer not found");
            }

            return response.ToActionResult();
        }
        
        [HttpPost]
        public virtual ActionResult Add(EditCustomerCommand command)
        {
            var response = new JsonResponse(true);
            this.customerManager.CreateCustomer(command);
            return response.ToActionResult();
        }

        [HttpPost]
        public virtual ActionResult Modify(EditCustomerCommand command)
        {
            var response = new JsonResponse(true);
            this.customerManager.EditCustomer(command);
            return response.ToActionResult();
        }

        [HttpPost]
        public virtual ActionResult Delete(int id)
        {
            var response = new JsonResponse(true);
            this.customerManager.DeleteCustomer(id);
            return response.ToActionResult();
        }

        public virtual ActionResult Lookup(string term)
        {
            var response = new JsonResponse(true, this.customerQueries.GetLookup(term));
            return response.ToActionResult();
        }
    }
}
